import React from 'react';
import {Icon, Input, Table, Button, message, Popconfirm, Tag} from 'antd';
import SubEditCell from '../EditCell/SubEditCell';

import {addCat} from "../../services/showServer";
import {deleteCat} from "../../services/showServer";
import {updateCat} from "../../services/showServer";

import styles from './table.less';

class CatEditListContainer extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      subId: '',
      subName: '',
      filterDropdownVisible: false,
      searchText: '',
      dataFilter: [],
      dataSource: [],
    };
  }

  onInputChange(e) {
    this.setState({
      searchText: e.target.value
    });
  }

  onFilterDropdownVisibleChange(visible) {
    this.setState({
      filterDropdownVisible: visible
    });
  }

  onSearch() {
    const { searchText, dataFilter} = this.state;
    const reg = new RegExp(searchText, 'gi');
    this.setState({
      filterDropdownVisible: false,
      dataSource: dataFilter.map((record) => {
        const match = record.name.match(reg);
        if (!match) {
          return null;
        }
        return {
          ...record,
        };
      }).filter(record => !!record),
    });
  }

  onCellChange = (index, key) => {
    return (value) => {
      const dataFilter = [...this.state.dataFilter];
      const dataSource = [...this.state.dataSource];
      const id = dataSource[index]['id'];
      var name = dataSource[index]['name'];
      var comment = dataSource[index]['comment'];
      if (key == 'name') {
        name = value;
      } else if (key == 'comment') {
        comment = value;
      }
      var cat = {
        "id": id,
        "name": name,
        "comment": comment
      }

      updateCat(cat).then(function (res) {
        //更新成功后刷新页面数据
        if (res.status == 200) {
          dataFilter[index][key] = value;
          dataSource[index][key] = value;
          this.setState({
            dataFilter: dataFilter,
            dataSource: dataSource
          });
        } else {
          message.error('更新分类失败', 2.5);
        }
      }.bind(this));

    };
  }

  onDelete = (index) => {
    return () => {
      const dataFilter = [...this.state.dataFilter];
      const dataSource = [...this.state.dataSource];
      const id = dataSource[index]['id'];
      deleteCat(id).then(function (res) {
        //更新成功后刷新页面数据
        if (res.status == 200) {
          dataFilter.splice(index, 1);
          dataSource.splice(index, 1);
          this.setState({
            dataFilter: dataFilter,
            dataSource: dataSource
          });
        } else {
          message.error('删除分类失败', 2.5);
        }
      }.bind(this));
    };
  }

  handleAdd = () => {
    const {dataFilter, dataSource, subId} = this.state;
    const cat = {
      "subId": subId,
      "category": {
        "id": "",
        "name": "新分类",
        "comment": "分类说明"
      },
    };

    addCat(cat).then(function (res) {
      //更新成功后刷新页面数据
      if (res.status == 200) {
        return res.json();
      } else {
        message.error('添加分类失败', 2.5);
      }
    }).then(function (data) {
      this.setState({
        dataFilter: [...dataFilter, data],
        dataSource: [...dataSource, data],
      });
    }.bind(this));
  }

  render() {

    const {dataSource} = this.state;

    const pagination = {
      total: dataSource.length,
      showSizeChanger: true,
    };

    const columns = [{
      title: '分类',
      key: 'name',
      dataIndex: 'name',
      width: '20%',
      render: (text, record, index) => (
        <SubEditCell
          value={text}
          onChange={this.onCellChange(index, 'name')}
        />
      ),
      filterDropdown: (
        <div className={styles.custom_filter_dropdown}>
          <Input
            placeholder=""
            value={this.state.searchText}
            onChange={this.onInputChange.bind(this)}
            onPressEnter={this.onSearch.bind(this)}
          />
          <Button type="primary" onClick={this.onSearch.bind(this)}>查询</Button>
        </div>
      ),
      filterDropdownVisible: this.state.filterDropdownVisible,
      onFilterDropdownVisibleChange: this.onFilterDropdownVisibleChange.bind(this),
    }, {
      title: '分类说明',
      key: 'comment',
      dataIndex: 'comment',
      render: (text, record, index) => (
        <SubEditCell
          value={text}
          onChange={this.onCellChange(index, 'comment')}
        />
      ),
    }, {
      title: '操作',
      dataIndex: '',
      width: '10%',
      render: (text, record, index) => {
        return (
          this.state.dataSource.length > 1 ?
            (
              <div>
                <Popconfirm title="Sure to delete?" onConfirm={this.onDelete(index)}>
                  <Button type="primary" shape="circle" size="small" style={{background: '#D9534F', border: 0}}
                  >
                    <Icon style={{color: '#F0F0F0'}} type="cross"/>
                  </Button>
                </Popconfirm>
              </div>
            ) : null
        );
      },
    }];

    return (
      <div>
        <div style={{marginBottom: 16}}>
          <Button type="primary" style={{background: '#6B9D25', border: 0}}
                  onClick={this.handleAdd.bind(this)}>
            添加分类
          </Button>
        </div>
        <Table bordered size="middle" columns={columns} pagination={pagination}
               dataSource={dataSource} rowKey={record => record.id}/>
      </div>
    );
  }
}

export default CatEditListContainer;
